<?php
/**
 * TopAdmin
 * 版权所有 2018-2027 TopAdmin，并保留所有权利。
 * Author: TopAdmin <8355763@qq.com>
 * Date: 2019/8/2
 */
namespace app\admin\controller\system;

use app\admin\model\AuthGroup;
use app\admin\model\AuthDept;
use app\admin\model\AuthRule;
use app\admin\model\Admin;
use app\admin\model\Adminlog;
use app\admin\model\Menu as MenuModel;
use app\common\controller\Backend;
use app\common\traits\Curd;
use top\helper\SignHelper;
use top\helper\StringHelper;
use think\facade\Config;
use think\facade\Db;
use think\facade\Request;
use think\facade\Session;
use think\facade\View;
use util\Tree;

class Rule extends Backend
{
    use Curd;
    public $uid = '';
    public function initialize()
    {
        $this->uid = Session::get('admin.id');
        parent::initialize(); // TODO: Change the autogenerated stub
        $this->modelClass = new AuthRule();
    }
    /*-----------------------管理员管理----------------------*/
    // 菜单列表

    public function index()
    {
        if ($this->request->isAjax()) {
            $tree = new Tree();
            $tree->icon = array('', '', '');
            $tree->nbsp = '';
            $result = AuthRule::order(array('pid', 'sort' => 'asc'))->select()->toArray();

            $tree->init($result);
            $_list = $tree->getTreeList($tree->getTreeArray(0), 'title');
            $total = count($_list);
            $result = array("code" => 0, "count" => $total, "data" => $_list);
            return json($result);
        }
        return view('');

    }


    // 权限增加
    public function add()
    {
        if (Request::isPost()) {
            $data = $this->request->post();
            if (empty($data['title'])) {
                $this->error(lang('rule name cannot null'));
            }
            if (empty($data['sort'])) {
                $this->error(lang('sort').lang(' cannot null'));
            }
            $data['icon'] = $data['icon']?$data['icon']:'fa fa-adjust';
            if(strpos(trim($data['href'],'/'),'admin/')===false){
                $data['href'] = 'admin/'.trim($data['href'],'/');
            }
            if ($this->modelClass->create($data)) {
                $this->success(lang('add success'),url('system.rule/index'));
            } else {
                $this->error(lang('add fail'));
            }
        } else {
            $list = Db::name('auth_rule')
                ->order('sort ASC')
                ->select();
            $list = $this->modelClass->cateTree($list);
            $rule = '';
            if(Request::get('rule_id')){
                $rule = Db::name('auth_rule')
                    ->find(Request::get('rule_id'));
            }
            $view = [
                'info' => null,
                'ruleList' => $list,
                'rule' =>$rule,
            ];
            View::assign($view);
            return view('add');
        }
    }

    //权限修改
    public function edit()
    {
        if (request()->isPost()) {
            $data = Request::param();
            $data['icon'] = $data['icon']?$data['icon']:'fa fa-adjust';
            if(strpos(trim($data['href'],'/'),'admin/')===false){
                $data['href'] = 'admin/'.trim($data['href'],'/');
            }
            $model = new AuthRule();
            $model->edit($data);
            $this->success(lang('edit success'), url('system.rule/index'));
        } else {
            $list = Db::name('auth_rule')
                ->order('sort asc')
                ->select();
            $list = $this->modelClass->cateTree($list);
            $id = Request::param('id');
            $info = $this->modelClass->find($id)->toArray();
            $rule = '';
            if(Request::get('rule_id')){
                $rule = Db::name('auth_rule')
                    ->find(Request::get('rule_id'));
            }
            $view = [
                'info' => $info,
                'ruleList' => $list,
                'rule' => $rule,
            ];
            View::assign($view);
            return view('add');
        }
    }

    public function quick(){
        $admin_rule = AuthRule::field('id, pid, title')
            ->where('menu_status',1)
            ->order('sort asc')->cache(3600)
            ->select()->toArray();
        $rules = AuthRule::where('quick',1)->field('id')->select()->toArray();
        $result = implode(',',array_column($rules,'id')); //数组转字符串
        $list = $this->modelClass->authChecked($admin_rule, $pid = 0, $result);
        $view = [
            'list' => $list,
        ];
        View::assign($view);
        return view();
    }

    // 用户组保存权限
    public function setQuick()
    {
        $rules = $this->request->post('rules');
        if (empty($rules)) {
            $this->error(lang('please choose rule'));
        }
        $rules = AuthRule::authNormal($rules);
        // 先找在quick为1的更新quick为0
        $quicks = AuthRule::where('quick',1)->field('id')->select()->toArray();
        foreach ($quicks as $k=>$v){
            $res = AuthRule::update(['quick' => 0], ['id' => $v['id']]);
        }
        // 再更新已选的quick为1
        foreach ($rules as $k=>$v){
            $res = AuthRule::update(['quick' => 1], ['id' => $v['id']]);
        }
        if ($res) {
            $this->success(lang('menu set successfully'),url('admin/index/main'));
        } else {
            $this->error(lang('rule assign fail'));
        }
    }

}